<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');

/**
 * Extension for: TYPOlight webCMS
 *
 * The TYPOlight webCMS is an accessible web content management system that
 * specializes in accessibility and generates W3C-compliant HTML code. It
 * provides a wide range of functionality to develop professional websites
 * including a built-in search engine, form generator, file and user manager,
 * CSS engine, multi-language support and many more. For more information and
 * additional TYPOlight applications like the TYPOlight MVC Framework please
 * visit the project website http://www.typolight.org.
 *
 * PHP version 5
 * @copyright  Christian Wenzel/Fred Bliss 2007 / computino.de Webservice 2008
 * @author     Christian Wenzel <wenzel@saiga.de>
 * @author     Fred Bliss <fred@stevensdesign.com>
 * @author     Markus Milkereit <markus@computino.de>
 * @package    Boxes
 * @license    GPL
 * @filesource
 */


/**
 * Class: ModuleBoxes
 *
 * @copyright  Christian Wenzel/Fred Bliss 2007 / computino.de Webservice 2008
 * @author     Christian Wenzel <wenzel@saiga.de>
 * @author     Fred Bliss <fred@stevensdesign.com>
 * @author     Markus Milkereit <markus@computino.de>
 *
 * Based on the class tl_boxen by Christian Wenzel
 * Class modification notes
 * Module has been updated to support more of the typolight fields. The following fields have been added:
 * Headline - Actually a 2-column array, Headline provides the ability to apply a label as well as indicating which of the
 * h-series tags (e.g. h1, h2, h3) to use to style the headline.
 * Space - CSS margins above or below box element
 * cssID - Actually a 2-column array, cssID provides the ability to apply classes and/or id labels for futher styling
 *
 * All box modules follow their own mod_boxen template, which wraps around individual boxes.
 * All boxes within a single module are now displayed according to the mod_boxen_items template, which resides within
 * the wrapper class, mod_contentbox
 *
 * It should be noted that all of the additional functionality came from the ContentElement class located in modules/frontend.
 * Aside from the modifications made in this file, I modified the template file accordingly to support the additional
 * attributes.  I also renamed the template file to be more in-line with the standard Typolight approach.  Not necessary, just
 * my personal preference.
 *
 *
 */

class ModuleBoxes extends Module
{

  /**
   * Template
   * @var string
   */
  protected $strTemplate = 'mod_box';

  /**
   * Display a wildcard in the back end
   * @return string
   */
  public function generate()
  {
    if (TL_MODE == 'BE')
    {
      $objTemplate = new BackendTemplate('be_wildcard');
      $objTemplate->wildcard = '### CONTENT BOXES ###';
      $objTemplate->title = $this->headline;
			$objTemplate->id = $this->id;
			$objTemplate->link = $this->name;
			$objTemplate->href = 'typolight/main.php?do=modules&amp;act=edit&amp;id=' . $this->id;
      return $objTemplate->parse();
    }

    $objRows = $this->Database->prepare("SELECT COUNT(*) as itemCount FROM tl_boxen WHERE modul_id=?")
                  ->limit(1)
                  ->execute($this->id);

    // Avoid an error due an empty result set from $objRows
    if ($objRows->itemCount > 0)
    {
      return parent::generate();
    }else{
      return;
    }
  }

  /**
   * Generate module
   */
  protected function compile()
  {
    global $objPage;

    //Generate our items html
    $this->Template->items = $this->renderBoxes($this->id);
  }

  protected function renderBoxes($module_id)
  {
    $this->import('String');
    //Used to borrow the function encodeEmail for rendering html.  This may or may not be
    //necessary to do, as another function may exist somewhere that is more appropriate.
    global $objPage;

    $items = array();

    $objboxen = $this->Database->prepare("SELECT * FROM tl_boxen WHERE modul_id=? ORDER BY position ASC")
                  ->execute($module_id);

    $objTemplate = new FrontendTemplate('mod_box_items');

    while ($objboxen->next())
    {
      $pages = unserialize($objboxen->pages);

      $space = deserialize($objboxen->space);

      $cssID = deserialize($objboxen->cssID, true);

      // Headlines are 2-column arrays, so we handle each column accordingly while building the $arrboxen array.
      $arrHeadline = deserialize($objboxen->headline);

      // This helps trap the invalid argument warning that occurs if no page is selected for a box
      // The invalid argument occurs because a null value for pages throws a warning.
      if (!empty($pages))  
      {          
        if (in_array($objPage->id, $pages))
        {
          // Space is a 2-column array as well, and we apply each column to it's corresponding css attribute.
          // Margin
          if (strlen($space[0]))
          {
            //Sets the space above requirement
            $style[] = 'margin-top:'.$space[0].'px;';
          }

          if (strlen($space[1]))
          {
            //Sets the space below requirement
            $style[] = 'margin-bottom:'.$space[1].'px;';
          }

          if (strlen($this->align))
          {
            $style[] = 'text-align:'.$this->align.';';
          }

          $size = deserialize($objboxen->size);
          $arrImageSize = @getimagesize(TL_ROOT . '/' . $objboxen->singleSRC);

          // Adjust image size in the back end
          if (TL_MODE == 'BE' && $arrImageSize[0] > 640 && ($size[0] > 640 || !$size[0]))
          {
            $size[0] = 640;
            $size[1] = floor(640 * $arrImageSize[1] / $arrImageSize[0]);
          }

          // Adjust size for use in frontend
          $src = $this->getImage($this->urlEncode($objboxen->singleSRC), $size[0], $size[1]);

          if (($imgSize = @getimagesize(TL_ROOT . '/' . $src)) !== false)
          {
            $imgSizeAttribute = ' ' . $imgSize[3];
          }

          /*
           * create href-link for fullsize or user-defined image-link
           * if user-defined link (imageUrl) is active, fullsizve-image is overwritten
           * added by christian wenzel @08-06-05
           */
          if ($objboxen->fullsize AND strlen($objboxen->imageUrl) == 0) {
            $href = $objboxen->singleSRC;
            $fullsize = true;
          }
          elseif (strlen($objboxen->imageUrl)) {
            $href = $objboxen->imageUrl;
            $fullsize = false;
          }
          else {
            $href = '';
          }

          // create array for use in template
          $items[] = array
          (
            'headline'    => is_array($arrHeadline) ? $arrHeadline['value'] : $arrHeadline,
            'h1'          => is_array($arrHeadline) ? $arrHeadline['unit'] : 'h1',
            'space'       => $space,
            'style'       => count($style) ? implode(' ', $style) : '',
            'cssID'       => strlen($cssID[0]) ? ' id="' . $cssID[0] . '"' : '',
            'class'       => strlen($cssID[1]) ? ' ' . $cssID[1] : '',
            'addImage'    => $objboxen->addImage ? true : false,
            'imgsize'     => $imgSizeAttribute,
            'width'       => (strlen($objBoxen->singleSRC) ? $arrImageSize[0] : 0),
            'height'      => (strlen($objBoxen->singleSRC) ? $arrImageSize[1] : 0),
            'src'         => $src,
            'href'        => (strlen($href) ? $href : false),
            'size'        => deserialize($objboxen->size),
            'margin'      => $this->generateMargin(deserialize($objboxen->imagemargin), 'padding'),
            'float'       => in_array($objboxen->floating, array('left', 'right')) ? sprintf(' float:%s;', $objboxen->floating) : '',
            'addBefore'   => $objboxen->floating != 'below',
            'caption'     => $objboxen->caption,
            'alt'         => specialchars($objboxen->alt),
            'fullsize'    => $fullsize,
            'imagelink'   => (strlen($objBoxen->imageUrl) ? true : false),
            'content'     => $this->String->encodeEmail($objboxen->content)
          );
        }
      }
    }

    /*
     * now that we have all the boxes that should be displayed on the current page,
     * add some css-classes (first, last) for easier formatting
     */
    if(count($items) >= 1){
      $items[0]['class'] .= ' first';
      $items[count($items)-1]['class'] .= ' last';
    }

    $objTemplate->items = $items;
    return count($items) ? $objTemplate->parse() : '';
  }
}